import { stringify } from 'querystring';
import { history, Reducer, Effect } from 'umi';

import { onlyLogin, checkUser } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';

export interface StateType {
  status?: 'ok' | 'error';
  currentAuthority?: 'user' | 'guest' | 'admin' | 'agency';
  users?: Array<LoginUserItemType>; 
}

export interface LoginUserItemType {
  identifying: string,
  name: string,
  oid: string,
  phone: string,
  token: string,
  type: number,
  uid: number,
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
    chooseUser: Effect;
    switch: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
    selectUsers: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(onlyLogin, payload);
      // console.log('【登录结果】', response);
      if (response.code == 0) {
        // 登录成功，获取登录用户
        const userRes = yield call(checkUser, response.data.token);
        if (userRes.code == 0) {
          // 选择登录用户
          yield put({
            type: 'selectUsers',
            payload: userRes.data,
          })
        }
      }
    },
    // 切换账号
    *switch(_, { call, put }) {
        const token = localStorage.getItem('agency_token');  
        // 登录成功，获取登录用户
        const userRes = yield call(checkUser, token);
        if (userRes.code === 0) {
          // 选择登录用户
          yield put({
            type: 'selectUsers',
            payload: userRes.data,
          })
        }
      
    },
    // 选择用户后登录
    *chooseUser({ payload}, { call, put}) {
      // 获取登录信息
      // console.log('【用户信息】', payload);
      const user = payload;
      yield put({
        type: 'selectUsers',
        payload: null,
      })
      
      yield put({
        type: 'changeLoginStatus',
        payload: user,
      });

      yield put({
        type: 'user/saveCurrentUserToken',
        payload: {
          token: user.token,
          id: user.id,
          user_type: user.user_type,
        },
      })

      // Login successfully
      if (payload.token) {
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        message.success('🎉 🎉 🎉  登录成功！');
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }
        // window.location.href = '/';
        history.replace(redirect || '/');
      }
    },
    *logout(_, { put }) {
      const { redirect } = getPageQuery();
      yield put({
        type: 'selectUsers',
        payload: null,
      })
      localStorage.setItem('agency_id', "");
      localStorage.setItem('agency_user_type', "");
      localStorage.setItem('agency_token', "");
      localStorage.setItem('agency_authority', "");
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },

  reducers: {
    // 设置权限
    changeLoginStatus(state, { payload }) {
      let role: StateType["currentAuthority"] = "guest";
      if (payload.user_type == 1) {
        // 代理登录
        role = "agency"
        setAuthority(role); 
      }
      return {
        ...state,
        currentAuthority: role,
      };
    },
    // 设置可以登录用户
    selectUsers(state, { payload }) {
      return {
        ...state,
        users: payload,
      }
    },
  },
};

export default Model;
